package cn.demoframe.test.utils;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FileToolkit {
	private static final Logger logger = LoggerFactory.getLogger(Thread.currentThread().getStackTrace()[1].getClassName());
	
    public static void main(String[] args) {
        // long start = System.currentTimeMillis();
        // copy("E:/临时资料/wifi2.rar",
        // "C:/Users/Administrator/Documents/wifi2_cp.rar");
        // long end = System.currentTimeMillis();
        // System.out.println("nio 用时： " + (end - start));

        // writeTextFile("e:/1.txt", "232131");
        
//        String text = readTextFile("e:/hibernate.cfg.xml");
//        System.out.println(text);
//        System.out.println(FileToolkit.getFileBase64("D:\\pic_file\\th.jpg"));
//        System.out.println(FileToolkit.getFileBase64URL("http://localhost:8080/test/11111"));
        System.out.println(FileToolkit.readTextFile(FileToolkit.class.getResource("../order/vmodel/emailFormat.html").getPath()));
    }

    public static String readTextFile(String dist) {
        File f = new File(dist);
        StringBuilder sbuf = new StringBuilder();
        InputStreamReader read = null;
        try {
            read = new InputStreamReader(new FileInputStream(f), "UTF-8");
            BufferedReader reader = new BufferedReader(read);
            String line = null;
            while ((line = reader.readLine()) != null) {
                if ("".equals(line)) {// 去除空行
                    continue;
                }
                sbuf.append(line).append("\n");
            }
            reader.close();
        } catch (UnsupportedEncodingException e) {
            logger.error("编码错误", e);
        } catch (FileNotFoundException e) {
            logger.error("找不到文件", e);
        } catch (IOException e) {
            logger.error("读取异常", e);
        } finally {
            try {
            	if(read != null) {
            		read.close();
            	}
            } catch (IOException e) {
                logger.error("关闭异常", e);
            }
        }
        return sbuf.toString();
    }

    public static void writeTextFile(String dist, String content) {
        File f = new File(dist);
        try {
            if (!f.exists()) {
                f.getParentFile().mkdirs();
                f.createNewFile();
            }
            OutputStream os = new FileOutputStream(f);
            OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
            BufferedWriter bw = new BufferedWriter(osw);
            bw.write(content);
            bw.close();
        } catch (Exception e) {
        	logger.error("文件写入失败, dist=" + dist + ", content=" + content, e);
        }
    }

    public static void copy(String src, String dist) {
        try {
            File srcFile = new File(src);
            File distFile = new File(dist);
            if (distFile.exists()) {
                distFile.delete();
            }

            FileInputStream fin = new FileInputStream(srcFile);
            FileOutputStream fout = new FileOutputStream(distFile);
            FileChannel inChannel = fin.getChannel();
            FileChannel outChannel = fout.getChannel();
            int ByteBufferSize = 1024 * 100;
            ByteBuffer buff = ByteBuffer.allocate(ByteBufferSize);

            while (inChannel.read(buff) > 0) {
                buff.flip();
                if (inChannel.position() == inChannel.size()) {// 判断是不是最后一段数据
                    int lastRead = (int) (inChannel.size() % ByteBufferSize);
                    byte[] bytes = new byte[lastRead];
                    buff.get(bytes, 0, lastRead);
                    outChannel.write(ByteBuffer.wrap(bytes));
                    buff.clear();
                } else {
                    outChannel.write(buff);
                    buff.clear();
                }
            }// 这个使用FileChannel 自带的复制
            // outChannel.transferFrom(inChannel, 0, inChannel.size());
            outChannel.close();
            inChannel.close();
            fin.close();
            fout.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取网络文件的Base64
     */
    public static String getFileBase64URL(String fileUrl) {	
        InputStream in = null;
        byte[] data = null;
        //读取图片字节数组
        try {
            URL url = new URL(fileUrl);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod("GET");
            if(conn.getResponseCode() == 200) {
            	in = conn.getInputStream();
            	BufferedInputStream bufin = new BufferedInputStream(in);  
                int buffSize = 1024;  
                ByteArrayOutputStream out = new ByteArrayOutputStream(buffSize);  
                byte[] temp = new byte[buffSize];  
                int size = 0;  
                while ((size = bufin.read(temp)) != -1) {  
                    out.write(temp, 0, size);  
                }  
                bufin.close();  
                data = out.toByteArray();  
            } else {
            	logger.info("读取网络文件的Base64，返回失败。fileUrl="+fileUrl+",conn.getResponseCode="+conn.getResponseCode());
            	return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            if(in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return CryptToolkit.base64Encoder(data);//返回Base64编码过的字节数组字符串
        
    }

    /**
     * 读取本地文件的Base64
     */
    public static String getFileBase64(String filePath) {
        InputStream in = null;
        byte[] data = null;
        //读取图片字节数组
        try {
            in = new FileInputStream(filePath);
            data = new byte[in.available()];
            in.read(data);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            if(in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return CryptToolkit.base64Encoder(data);//返回Base64编码过的字节数组字符串
    }

    public static boolean GenerateFileFromBase64Str(String str, String filePath) {
        //对字节数组字符串进行Base64解码并生成文件
        if (str == null) //文件数据为空
            return false;
        OutputStream out = null;
        try {
            //Base64解码
            byte[] b = CryptToolkit.base64Decoder1(str);
            for(int i=0;i<b.length;++i) {
                if(b[i]<0) {//调整异常数据
                    b[i]+=256;
                }
            }
            //生成文件
            out = new FileOutputStream(filePath);
            out.write(b);
            out.flush();
            return true;
        } catch (Exception e) {
            return false;
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
